package jobs

import (
	"errors"
	"fmt"
	"youbei/dao"
	"youbei/utils/mail"

	"github.com/beego/beego/httplib"
)

//Jobs ...
func Jobs(i string) func() error {
	return func() error {
		tmcs := []dao.TaskMountedCron{}
		m := new(mail.MailConn)
		if err := dao.Localdb().Where("cid=?", i).Find(&tmcs); err != nil {
			m.SendMail("备份失败,查询计划任务失败", err.Error())
		}
		for _, v := range tmcs {
			go func(tid string) {
				if bol, err := dao.Localdb().ID(v.Tid).Exist(new(dao.Task)); err == nil && bol {
					if err := Backup(tid); err != nil {
						m.SendMail("备份失败", err.Error())
					}
				}
			}(v.Tid)

		}

		return nil
	}
}

//Backup ...
func Backup(TaskID string) error {
	task := dao.Task{}
	if bol, err := dao.Localdb().ID(TaskID).Get(&task); err != nil {
		return err
	} else {
		if !bol {
			return errors.New("任务不存在")
		}
	}

	if res, err := dao.NewLog(task.ID); err != nil {
		return err
	} else {
		task.LogId = res.ID
	}

	rstts := []dao.RemoteStorageToTask{}
	if err := dao.Localdb().Where("tid=?", TaskID).Find(&rstts); err != nil {
		return err
	}
	if len(rstts) > 0 {
		for _, v := range rstts {
			rs := dao.RemoteStorage{}
			if bol, err := dao.Localdb().ID(v.Rid).Get(&rs); err != nil {
				continue
			} else {
				if !bol {
					continue
				}
			}
			rlog, err := dao.AddNewRemoteSendLog(task.LogId, task.ID, v.Rid)
			if err != nil {
				continue
			}
			rs.Rlogid = rlog.ID
			task.RemoteStorages = append(task.RemoteStorages, rs)
		}

	}
	client := dao.Host{}
	if bol, err := dao.Localdb().ID(task.ClientId).Get(&client); err != nil {
		return err
	} else {
		if !bol {
			return errors.New("获取记录为空")
		}
	}
	req := httplib.Post("http://" + client.HostAddr + ":" + client.Port + "/api/runjob")
	req.Header("token", client.Token)
	req.Header("Content-Type", "application/json")
	req.JSONBody(task)
	fmt.Println(req.String())
	return nil
}
